package com.biz.feign.interceptor;

import feign.*;
import lombok.extern.slf4j.*;
import org.springframework.web.context.request.*;

import javax.servlet.http.*;
import java.util.*;

/**
 * @Description
 *    Feign 拦截器
 * @Author liuxi
 * @Date 2024/5/19
 **/
@Slf4j
public class FeignAuthRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //如果在Cookie内通过如下方式取
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                requestTemplate.header(cookie.getName(), cookie.getValue());
            }
        }
        //如果放在header内通过如下方式取
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                //遍历请求头里面的属性字段
                if ("cookie".equalsIgnoreCase(name) || "JSESSIONID".equalsIgnoreCase(name) ||
                        "token".equalsIgnoreCase(name)) {
                    String value = request.getHeader(name);
                    requestTemplate.header(name, value);
                }
            }
        }
    }

}
